import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Checkbox, message, Spin, Tabs } from 'antd';
import { UserOutlined, LockOutlined, GithubOutlined, GoogleOutlined, MailOutlined, SafetyOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { sendVerificationCode, register, login, verifyCode } from '../api/auth';
import { useAuth, UserRole } from '../context/AuthContext';

const { TabPane } = Tabs;

const Login: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [rememberMe, setRememberMe] = useState<boolean>(true);
  const navigate = useNavigate();
  const { login: authLogin, setUser, setIsAuthenticated } = useAuth();
  const [passwordForm] = Form.useForm();  // 密码登录表单
  const [codeForm] = Form.useForm();      // 验证码登录表单
  const [registerForm] = Form.useForm();  // 注册表单
  const [isLogin, setIsLogin] = useState(true);
  const [countdown, setCountdown] = useState(0);
  const [sendingCode, setSendingCode] = useState(false);
  const [activeTab, setActiveTab] = useState('password');

  // 倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  const handleSendVerificationCode = async () => {
    try {
      // 根据当前激活的标签页选择正确的表单
      const form = activeTab === 'code' ? codeForm : registerForm;
      const email = form.getFieldValue('email');
      if (!email) {
        message.error('请先输入邮箱地址！');
        return;
      }
      
      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        message.error('请输入有效的邮箱地址！');
        return;
      }

      // 先开始倒计时
      setCountdown(60);
      setSendingCode(true);
      
      const response = await sendVerificationCode(email);
      message.success('验证码已发送到您的邮箱，请注意查收！');
    } catch (error: any) {
      const errorMessage = error.response?.data?.detail || error.message || '发送验证码失败，请稍后重试！';
      message.error(errorMessage);
      console.error('发送验证码失败:', error);
      // 发送失败时重置倒计时
      setCountdown(0);
    } finally {
      setSendingCode(false);
    }
  };

  const onPasswordLogin = async (values: { email: string; password: string }) => {
    try {
      setLoading(true);
      const response = await login({
        email: values.email,
        password: values.password
      });
      message.success('登录成功，正在跳转...');
    
      // 使用AuthContext的login方法
      await authLogin(values.email, values.password);
      
      // 根据用户角色进行导航
      if (response.user.is_admin) {
        navigate('/home/permissions');
      } else {
        navigate('/api/v1/home');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.detail || error.message || '登录失败，请重试';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const onCodeLogin = async (values: { email: string; verificationCode: string }) => {
    try {
      setLoading(true);
      // 直接使用验证码登录
      const response = await login({
        email: values.email,
        code: values.verificationCode
      });
      
      message.success('登录成功，正在跳转...');
      
      // 直接使用登录响应中的用户信息更新认证状态
      const { user, token } = response;
      if (token) {
        localStorage.setItem('token', token);
      }
      
      // 更新认证状态
      setUser({
        id: user.id,
        email: user.email,
        username: user.username,
        role: user.is_admin ? UserRole.ADMIN : UserRole.USER,
        is_active: true,
        password_hash: '',
        created_at: '',
        updated_at: '',
        is_admin: user.is_admin
      });
      setIsAuthenticated(true);
      
      // 最后进行导航
      if (user.is_admin) {
        navigate('/home/permissions');
      } else {
        navigate('/api/v1/home');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.detail || error.message || '登录失败，请重试';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const onRegister = async (values: any) => {
    try {
      setLoading(true);
        const response = await register({
          email: values.email,
          password: values.password,
        username: values.username,
          code: values.verificationCode
        });
        message.success('注册成功！请登录以继续。');
        setIsLogin(true);
      registerForm.resetFields();
    } catch (error: any) {
      console.error('注册失败:', error);
      const errorMessage = error.response?.data?.detail || error.message || '注册失败，请重试';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const switchMode = () => {
    setIsLogin(!isLogin);
    passwordForm.resetFields();
    codeForm.resetFields();
    registerForm.resetFields();
    message.info(isLogin ? '切换到注册模式' : '切换到登录模式');
  };

  return (
    <div className="login-container">
      <div className="login-content">
        <div className="login-left">
          <div className="login-logo">
            <img src="/images/logo.svg" alt="Logo" className="brand-logo" />
            <h1>TellTech</h1>
          </div>
          
          <div className="content-wrapper">
            <div className="workspace-image"></div>
            <div className="login-welcome">
              <h2>言宇</h2>
              <p>您的工作流管理后台</p>
            </div>
          </div>
        </div>
        
        <div className="login-right">
          <div className="login-form-wrapper">
            <h2 className="login-title">{isLogin ? '登录' : '注册'}</h2>
            {isLogin ? (
              <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ height: '320px' }}>
                <TabPane tab="密码登录" key="password">
                  <Form
                    form={passwordForm}
                    name="passwordLogin"
                    onFinish={onPasswordLogin}
                    initialValues={{ email: '', password: '', remember: true }}
                    size="large"
                    style={{ 
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between'
                    }}
                  >
                    <div>
                      <Form.Item
                        name="email"
                        rules={[
                          { required: true, message: '请输入邮箱或用户名！' }
                        ]}
                      >
                        <Input
                          prefix={<MailOutlined className="site-form-item-icon" />}
                          placeholder="邮箱/用户名"
                          autoComplete="email"
                        />
                      </Form.Item>

                      <Form.Item
                        name="password"
                        rules={[
                          { required: true, message: '请输入密码！' },
                          { min: 6, message: '密码长度不能少于6个字符！' }
                        ]}
                      >
                        <Input.Password
                          prefix={<LockOutlined className="site-form-item-icon" />}
                          placeholder="密码"
                          autoComplete="current-password"
                        />
                      </Form.Item>
                    </div>

                    <div>
                      <Form.Item>
                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Checkbox
                            checked={rememberMe}
                            onChange={(e) => setRememberMe(e.target.checked)}
                          >
                            记住我
                          </Checkbox>
                          <a onClick={() => message.info('请联系管理员重置密码')}>忘记密码？</a>
                        </div>
                      </Form.Item>

                      <Form.Item>
                        <Button
                          type="primary"
                          htmlType="submit"
                          loading={loading}
                          block
                          style={{ backgroundColor: '#0960bd', borderColor: '#0960bd' }}
                        >
                          登录
                        </Button>
                      </Form.Item>
                    </div>
                  </Form>
                </TabPane>
                <TabPane tab="验证码登录" key="code">
                  <Form
                    form={codeForm}
                    name="codeLogin"
                    onFinish={onCodeLogin}
                    initialValues={{ email: '', verificationCode: '' }}
                    size="large"
                    style={{ 
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between'
                    }}
                  >
                    <div>
                      <Form.Item
                        name="email"
                        rules={[
                          { required: true, message: '请输入邮箱！' },
                          { type: 'email', message: '请输入有效的邮箱地址！' }
                        ]}
                      >
                        <Input
                          prefix={<MailOutlined className="site-form-item-icon" />}
                          placeholder="邮箱"
                          autoComplete="email"
                        />
                      </Form.Item>

                      <Form.Item
                        name="verificationCode"
                        rules={[
                          { required: true, message: '请输入验证码！' },
                          { len: 6, message: '验证码必须是6位数字！' }
                        ]}
                      >
                        <Input
                          prefix={<SafetyOutlined className="site-form-item-icon" />}
                          placeholder="验证码"
                          suffix={
                            <Button
                              type="link"
                              disabled={countdown > 0 || sendingCode}
                              onClick={handleSendVerificationCode}
                              style={{ 
                                height: '100%',
                                padding: '0 15px',
                                margin: '-1px -15px',
                                border: 'none'
                              }}
                            >
                              {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                            </Button>
                          }
                        />
                      </Form.Item>
                    </div>

                    <div>
                      <Form.Item>
                        <Button
                          type="primary"
                          htmlType="submit"
                          loading={loading}
                          block
                          style={{ backgroundColor: '#0960bd', borderColor: '#0960bd' }}
                        >
                          登录
                        </Button>
                      </Form.Item>
                    </div>
                  </Form>
                </TabPane>
              </Tabs>
            ) : (
            <Form
                form={registerForm}
                name="register"
                onFinish={onRegister}
                initialValues={{ email: '', password: '', confirmPassword: '', verificationCode: '', username: '' }}
              size="large"
                style={{ 
                  height: '320px',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'space-between'
                }}
              >
                <div>
              <Form.Item
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱！' },
                  { type: 'email', message: '请输入有效的邮箱地址！' }
                ]}
              >
                <Input
                  prefix={<MailOutlined className="site-form-item-icon" />}
                  placeholder="邮箱"
                  autoComplete="email"
                />
              </Form.Item>

                  <Form.Item
                    name="username"
                    rules={[
                      { required: true, message: '请输入用户名！' },
                      { min: 2, message: '用户名至少2个字符！' },
                      { max: 20, message: '用户名最多20个字符！' },
                      { 
                        pattern: /^[^@]*$/,
                        message: '用户名包含非法字符！'
                      }
                    ]}
                  >
                    <Input
                      prefix={<UserOutlined className="site-form-item-icon" />}
                      placeholder="用户名"
                    />
                  </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码！' },
                      { min: 6, message: '密码长度不能少于6个字符！' }
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  placeholder="密码"
                      autoComplete="new-password"
                />
              </Form.Item>

                <Form.Item
                  name="verificationCode"
                  rules={[
                    { required: true, message: '请输入验证码！' },
                    { len: 6, message: '验证码必须是6位数字！' }
                  ]}
                >
                  <Input
                    prefix={<SafetyOutlined className="site-form-item-icon" />}
                    placeholder="验证码"
                    suffix={
                      <Button
                        type="link"
                        disabled={countdown > 0 || sendingCode}
                        onClick={handleSendVerificationCode}
                          style={{ 
                            height: '100%',
                            padding: '0 15px',
                            margin: '-1px -15px',
                            border: 'none'
                          }}
                      >
                        {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                      </Button>
                    }
                  />
                </Form.Item>
                  </div>

                <div>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                  style={{ backgroundColor: '#0960bd', borderColor: '#0960bd' }}
                >
                      注册
                </Button>
              </Form.Item>
                </div>
              </Form>
            )}

              <div className="login-links">
                <span>{isLogin ? '还没有账号？' : '已有账号？'}</span>
                <a onClick={switchMode}>{isLogin ? '立即注册' : '返回登录'}</a>
              </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login; 